<%--
  Created by IntelliJ IDEA.
  User: Li Chuanwei
  Date: 2023-07-17
  Time: 8:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户购物车</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css" media="all">
    <script src="${pageContext.request.contextPath}/static/layui/layui.js" charset="utf-8"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/fontawesome/css/all.css" media="all">
    <script src="${pageContext.request.contextPath}/static/js/showBigImage.js"></script>
    <style>
        body {
            background: rgb(234, 232, 235);
        }

        .mainContainer {
            margin-top: 5vh;
            margin-left: 11vw;
            width: 78vw;
            background: white;
            border: 1px solid #f2f2f2;
            border-radius: 10px;
            padding: 10px;
        }

        .centerContainer {
            margin-top: 1%;
            width: 100%;
        }

        .layui-card {
            border: 1px solid #f2f2f2;
            border-radius: 5px;
        }

        .icon {
            margin-right: 10px;
            color: #1aa094;
        }

        .layuimini-qiuck-module {
            text-align: center;
            margin-top: 10px
        }

        .layuimini-qiuck-module a i {
            display: inline-block;
            width: 100%;
            height: 60px;
            line-height: 60px;
            text-align: center;
            border-radius: 2px;
            font-size: 30px;
            background-color: #F8F8F8;
            color: #333;
            transition: all .3s;
            -webkit-transition: all .3s;
        }

        .layuimini-qiuck-module a cite {
            position: relative;
            top: 2px;
            display: block;
            color: #666;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            font-size: 14px;
        }

        .main_btn > p {
            height: 40px;
        }

        .goodsCard {
            width: 100%;
            height: 160px;
            border-radius: 5px;
            background: rgb(247, 249, 250);
            position: relative;
        }

        .goodsCard img {
            padding: 5px;
            border-radius: 10px;
            max-width: 10vw;
            max-height: 10vw;
            min-width: 10vw;
            min-height: 10vw;
        }

        .goodsContainer {
            padding: 10px;
        }

        .goodsText {
        }

        .goodsInfo {
            margin-top: 10px;
            font-size: 1.1em;
        }

        .goodsPrice {
            color: red;
            font-size: 2em;
            margin-top: 50%;
        }

        .layui-table-cell {
            text-align: center;
            height: auto !important;
            white-space: normal;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <!-- 头部 -->
        <div class="layui-row">
            <jsp:include page="../common/_top.jsp"></jsp:include>
        </div>

        <div class="mainContainer">

            <p style="font-size: 2em;margin-bottom: 20px;margin-top: 20px;font-family: 宋体;font-weight: bold;margin-left: 10px">
                <i class="fa fa-shopping-cart" style="color: red;margin-right: 10px"></i>购物车（全部${itemNum}）
            </p>
            <%-- 表头工具条--%>
            <script type="text/html" id="template-id">
                <div class="layui-btn-container">
                    <button class="layui-btn layui-btn-danger layui-btn-radius" id="buyOrder" lay-event="buyOrder"
                            style="margin-left: 100%">结算
                    </button>
                </div>
            </script>

            <%-- 商品名字--%>
            <script type="text/html" id="goodsName">
                <a href="${pageContext.request.contextPath}/goodsDetails?id={{d.goodsId}}"
                   style="color: red">{{d.name}}</a>
            </script>
            <%-- 商品图片列--%>
            <script type="text/html" id="goodsPic">
                <img src="${IMG_SERVER}/goods/{{d.pic}}" onclick="showBigImage(this)"
                     style="width: 100% ; height: 100%"
                     class="goodsPic">
            </script>

            <%-- 价格--%>
            <script type="text/html" id="price">
                <div class="layui-input-group">
                    <input type="text" id="price{{d.id}}" class="layui-input" value="{{d.price2}}"
                           style="text-align: center;border: none;background: none" disabled>
                </div>
            </script>

            <%-- 数量--%>
            <script type="text/html" id="num">
                <div class="layui-input-group">
                    <div class="layui-input-prefix" style="padding: 0">

                        <button id="minusBtn" class="layui-btn layui-btn-primary" onclick="minus({{d.id}})">-</button>
                    </div>
                    <input type="text" id="numberInput{{d.id}}" class="layui-input" value="{{d.storage}}"
                           style="text-align: center">
                    <div class="layui-input-suffix" style="padding: 0">
                        <button id="plusBtn" class="layui-btn layui-btn-primary" onclick="add({{d.id}})">+</button>
                    </div>
                </div>
            </script>

            <%-- 总金额--%>
            <script type="text/html" id="totalPrice">
                <div class="layui-input-group">
                    <input type="text" id="total{{d.id}}" class="layui-input" value="{{d.total}}"
                           style="text-align: center;border: none;color: red;background: none">
                </div>
            </script>

            <%-- 货物列表--%>
            <table class="layui-hide" id="goodsCarTable" lay-filter="goodsCarTableFilter"></table>

            <%-- 行内操作工具条--%>
            <script type="text/html" id="goodsCarTableBar">
                <a class="" lay-event="buy">购买</a><br>
                <a class="" lay-event="delete">删除</a>
            </script>
        </div>
    </div>
</div>

</div>

<script>
    // 减号按钮点击事件
    function minus(e) {
        var input = document.getElementById('numberInput' + e);
        var currentValue = parseInt(input.value);
        if (currentValue > 0) {
            input.value = currentValue - 1;
        }
        var total = document.getElementById('total' + e);
        var price = document.getElementById('price' + e);
        total.value = input.value.valueOf() * price.value.valueOf();
        total.value = parseFloat(total.value).toFixed(2);
        $.ajax({
            url: '${pageContext.request.contextPath}/user/cartItem/updateNum',
            type: 'GET',
            dataType: 'json',
            data: {
                id: e,
                amount: input.value
            },
            success: function (data) {

            },
            error: function (xhr, textStatus, errorThrown) {
                layer.msg('获取数据失败');
            }
        });
    };

    // 加号按钮点击事件
    function add(e) {
        var input = document.getElementById('numberInput' + e);
        var currentValue = parseInt(input.value);
        input.value = currentValue + 1;
        var total = document.getElementById('total' + e);
        var price = document.getElementById('price' + e);
        total.value = input.value.valueOf() * price.value.valueOf();
        total.value = parseFloat(total.value).toFixed(2);
        $.ajax({
            url: '${pageContext.request.contextPath}/user/cartItem/updateNum',
            type: 'GET',
            dataType: 'json',
            data: {
                id: e,
                amount: input.value
            },
            success: function (data) {

            },
            error: function (xhr, textStatus, errorThrown) {
                layer.msg('获取数据失败');
            }
        });
    };
</script>
<script>
    layui.use(['form', 'table', 'element', 'layer'], function (message) {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        dropdown = layui.dropdown;

        /**
         * 表格渲染
         */
        table.render({
            elem: '#goodsCarTable',
            request: {
                pageName: 'pageNum', // 页码的参数名称，默认：page
                limitName: 'pageSize' // 每页数据条数的参数名，默认：limit
            },
            where: {
                userId:${sessionScope.user.getId()}
            },
            defaultToolbar: [""],
            url: '${pageContext.request.contextPath}/user/cartItem/list',
            cols: [[
                {type: "checkbox"},
                {title: '序号', type: "numbers", align: "center"},
                {field: 'name', title: '商品名称', templet: "#goodsName"},
                {field: 'goodsId', title: '商品编号', hide: true},
                {field: 'pic', title: '商品主图', align: 'center', templet: "#goodsPic"},
                {field: 'price2', title: '价格', align: 'center', templet: "#price"},
                {field: 'storage', title: '数量', templet: "#num"},
                {field: 'total', title: '金额', templet: "#totalPrice"},
                {
                    title: '操作', toolbar: '#goodsCarTableBar', align: "center"
                }
            ]],
            loading: true,
            skin: 'nob',
            toolbar: '#template-id'
        });

        /**
         * 表格头部工具条事件
         */
        table.on('toolbar(goodsCarTableFilter)', function (obj) {
            if (obj.event === 'buyOrder') {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var data = checkStatus.data;
                var selectedGoodsIds = [];
                var selectedNums = [];
                for (var i = 0; i < data.length; i++) {
                    var row = data[i];
                    selectedGoodsIds.push(row.goodsId); // 假设id字段为id，你需要将其替换为实际的id字段名
                    selectedNums.push(document.getElementById('numberInput' + row.id).value);
                }
                if (selectedNums.length === 0)
                    layer.msg("未选中任何商品");
                else
                    window.location.href = "${pageContext.request.contextPath}/user/order/buyGoods?goodsIds=" + selectedGoodsIds + "&&Num=" + selectedNums;
            }

        });

        /**
         * 触发表格复选框选择
         */
        table.on('checkbox(goodsCarTable)', function (obj) {
            console.log(obj)
        });

        /**
         * 行内操作按钮事件
         */
        table.on('tool(goodsCarTableFilter)', function (obj) {
            var data = obj.data;
            /**
             * 查看详情
             */
            if (obj.event === 'buy') {

            }
            /**
             * 删除
             */
            if (obj.event === 'delete') {
                layer.confirm('确定移除购物车？', {icon: 3}, function () {
                    $.ajax({
                        url: '${pageContext.request.contextPath}/user/cartItem/deleteOne',
                        type: 'GET',
                        dataType: 'json',
                        data: {
                            id: data.id
                        },
                        success: function (data) {
                            layer.msg("移除成功");
                            //成功后重载数据
                            table.reload('goodsCarTable', {}, 'data');
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            layer.msg('获取数据失败');
                        }
                    });
                }, function () {

                });
            }
        });

    });
</script>
</body>
</html>